<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #whole {
            width: 300px;
            margin: 0 auto;
            text-align: center;
        }

        #main {
            width: 300px;
            height: 40px;
            border: 2px solid #ccc;
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        #result {
            height: 40px
        }

        #inp {
            border: none;
            width: 180px;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <div id="whole">
        <h2>验证码验证</h2>
        <div id="main">
            <input type="text" placeholder="请输入验证码" id="inp" />
            <img src="" alt="" id="img">
        </div>
        <button id="btn">验证</button>
        <p id="result"></p>
    </div>

</body>
<script>
    var inp = document.getElementById('inp');
    var img = document.getElementById('img');
    var btn = document.getElementById('btn');
    // var result = document.getElementById('result');

    // var answer = '';//用来存放请求的验证码图片的答案
    var name = '';//用来存放请求的验证码图片的名字

    // 接收id对象数组
    var array = [];

    request();

    // get请求获取验证码图片
    function request() {
        fetch('/token', {
            method: 'get',
        }).then(res => res.json()).then((res) => {
            console.log(res)
            name = res.name;
            var src = `/image/${res.name}`;
            img.src = src;

        })
    }

    // 实现点击验证码图片切换不同验证码
    img.onclick = function () {
        request();
    }

    // 验证用户输入的验证码是否正确
    btn.onclick = function () {
        // post用户
        fetch('/user', {
            method: 'post',
            body: JSON.stringify({ name: name, val: inp.value }),
            headers: {
                "Content-Type": "application/json"
            }

        }).then(res => res.text()).then(console.log(res))
    }
    inp.onfocus = function () {
        inp.style.outline = 'none'
    }



</script>

</html>